package com.wing.product.controller.app;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.enterprise.feign.EnterpriseClient;
import com.wing.enterprise.product.model.entity.CabInventoryProduct;
import com.wing.enterprise.product.model.request.CabInventoryProductForm;
import com.wing.platform.feign.PlatformClient;
import com.wing.platform.order.model.response.ProductVO;
import com.wing.product.model.entity.Product;
import com.wing.product.model.entity.ProductCategory;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.model.request.ProductDetailForm;
import com.wing.product.model.request.ProductForm;
import com.wing.product.model.response.ProductDetailVO;
import com.wing.product.service.MostUsedKnifeListService;
import com.wing.product.service.ProductDetailService;
import com.wing.product.service.ProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Validated
@Api(value = "App-常用刀具产品列表", tags = "App-常用刀具产品列表")
@RestController("appMostUsedKnifeListController")
@RequestMapping("cabProduct/app/mostUsedKnifeList")
@RequiredArgsConstructor
@Slf4j
public class MostUsedKnifeListController {

    private final PlatformClient platformClient;
    private final EnterpriseClient enterpriseClient;

    private final ProductService productService;
    private final ProductDetailService productDetailService;
    @Autowired
    private  MostUsedKnifeListService mostUsedKnifeListService;


    @ApiOperation(value = "查询所有常用刀具", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "skuCode", value = "商品SKU编码", defaultValue = "", example = "", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "skuName", value = "商品SKU名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "productName", value = "商品名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "productBrandName", value = "商品品牌名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<ProductDetailVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "id") String sort
            ,@RequestParam(defaultValue = "desc") String order
            ,String skuCode
            ,String skuName
            ,String productName
            ,String productBrandName
            ,String oldSkuCode
            ,String oldSpecCode
            , String startTime
            , String endTime
            , ProductCategory.CategoryType categoryType
            , ProductCategory.Type type
    ){
        Page<ProductDetail> pg = new Page<>(page, limit);
        Map paramMap=new HashMap();
        paramMap.put("sort", StrUtil.toUnderlineCase(sort));
        paramMap.put("order",StrUtil.toUnderlineCase(order));
        paramMap.put("skuCode",skuCode);
        paramMap.put("skuName",skuName);
        paramMap.put("productName",productName);
        paramMap.put("productBrandName",productBrandName);
        paramMap.put("oldSkuCode",oldSkuCode);
        paramMap.put("oldSpecCode",oldSpecCode);
        paramMap.put("startCreateTime",startTime);
        paramMap.put("endCreateTime",endTime);
        if(null != categoryType){
            paramMap.put("categoryType",categoryType.getValue());
        }
        if(null != type){
            paramMap.put("type",type.getValue());
        }
        IPage<ProductDetailVO> list =mostUsedKnifeListService.findAll(pg,paramMap);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    @ApiOperation(value = "删除常用刀具详情", notes = "删除")
    @DeleteMapping ("/delete/{ids}")
    public JsonResult delete(@PathVariable("ids") String ids) {//detail表直接删除即可，product表要看detail表删除的是否是最后一条根据productid,如果是product表删除对应产品

        try{
            mostUsedKnifeListService.deleteMostUsedKnifeList(ids);
            return JsonResult.success("删除成功");
        }catch (Exception e) {
            log.error("删除失败", e);
            return JsonResult.fail("删除失败"+e.getMessage());
        }
    }

    //平台列表
    @ApiOperation(value = "查询平台可导入产品", notes = "查询")
    @GetMapping("/queryFromPlatform")
    public  Object  queryFromPlatform(@RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit
            , @RequestParam(defaultValue = "create_time") String sort
            , @RequestParam(defaultValue = "asc") String order
            , @RequestParam(required = false) Long productTypeId
            , @RequestParam(required = false) String settledCompanyId
            , @RequestParam(defaultValue = "0") String status
            , @RequestParam(required = false) String name
            , @RequestParam(defaultValue = "0") Integer type
            , @RequestParam(required = false) String brandName
            , @RequestParam(required = false) String productCode
            , @RequestParam(required = false) Long productCategoryId
            , @RequestParam(required = false) Long productBrandId
            , @RequestParam(required = false) Long productUnitId
    ) {
        return platformClient.queryFromPlatform("",page,limit,sort,order,productTypeId,settledCompanyId,status,name,type,brandName,productCode,productCategoryId,productBrandId,productUnitId);
    }




    @ApiOperation(value = "批量导入", notes = "插入")
    @PostMapping("/addAll")
    public JsonResult addAll(@RequestBody List<List<ProductDetailForm>> list){//批量导入多个产品
        //先过滤数据，剔除已经导入过的数据
        for (int i=0;i<list.size();i++){
            for (int j = list.get(i).size() - 1; j >= 0; j--) {
                if (mostUsedKnifeListService.findAllDetailId().contains(list.get(i).get(j).getId())){
                    list.get(i).remove(j);
                }
            }
            if(list.get(i).size()==0){
                list.remove(i);
            }
        }
        if(list.size()==0){
            return JsonResult.success("数据已全部导入");
        }
        for (int i=0;i<list.size();i++){
            add(list.get(i));
        }
        return JsonResult.success("添加成功");
    }


    @ApiOperation(value = "导入常用刀具", notes = "企业导入")
    @PostMapping("/add")
    //单个规格和整个产品插入
    public JsonResult add(@RequestBody List<ProductDetailForm> list){
        for (int i=0;i<list.size();i++){
            ProductVO productVO = platformClient.queryProductFromPlatform("",list.get(i).getProductId()).getData(); //product表新增数据根据productId从平台端的product表查询获取
            if(mostUsedKnifeListService.existById(list.get(i).getProductId())!=null){//判断product表是否已经存在，已经存在就只在detail表插入新的细节信息
                list.get(i).setProductPic(productVO.getPicture())//sku图片取产品的图片
                        .setIdPlatform(list.get(i).getId())//记录在平台端的id
                        .setDataSourceType(ProductDetail.DataSourceType.platform)//数据来源从平台
                        .setProductId(Long.parseLong(mostUsedKnifeListService.existById(list.get(i).getProductId()).get("id").toString()))//表id自动生成 detail表的product_id要跟product表id对应
                        .setId(null);//表id自动生成
            }else {//不存在说明是第一次添加的产品product和detail表都新增
                Product product =new Product();
                CopyOptions copyOptions = CopyOptions.create()
                        .setEditable(Product.class)
                        .setIgnoreError(true)
                        .setIgnoreNullValue(true);
                BeanUtil.copyProperties(productVO, product, copyOptions);
                product.setDataSourceType(Product.DataSourceType.platform)
                        .setIdPlatform(product.getId())
                        .setId(null);
                list.get(i).setProductPic(productVO.getPicture())
                        .setIdPlatform(list.get(i).getId())
                        .setDataSourceType(ProductDetail.DataSourceType.platform)//数据来源从平台
                        .setId(null);
                if(!productService.save(product)){
                    return JsonResult.fail("添加失败");
                }
                //list.get(i).setProductId(product.getId());
                list.get(i).setProductId(Long.parseLong(mostUsedKnifeListService.existById(list.get(i).getProductId()).get("id").toString()));//表id自动生成 detail表的product_id要跟新生成的product表id对应
                if(productDetailService.add(list.get(i))==0){
                    return JsonResult.fail("添加失败");
                }
            }
            //库存表添加库存为0的记录
            CabInventoryProductForm cabInventoryProduct = new CabInventoryProductForm();
            cabInventoryProduct.setSkuCode(list.get(i).getSkuCode())
                    .setType(CabInventoryProduct.Type.knife)
                    .setSkuType(2);
            enterpriseClient.addCabInventoryProduct(cabInventoryProduct);
        }
        return JsonResult.success("添加成功");
    }




    @ApiOperation(value = "查询已经导入的产品", notes = "查询")
    @GetMapping("/queryExistProduct")
    public JsonResult queryExistProduct(){//查询detail表中的id，页面做判断，是否能导入
        List<String> list = mostUsedKnifeListService.findAllDetailId();//查询返回已经存在的所有id_platform
        return JsonResult.success(JsonResult.Code.SUCCESS.getCode(), "查询成功",list);
    }

    //
    @ApiOperation(value = "添加自采产品", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/addProduct")
    public JsonResult addProduct(@RequestBody  @Validated(ProductForm.Add.class) ProductForm productForm) {
        try {
            mostUsedKnifeListService.add(productForm);
            return JsonResult.success("添加成功");
        }catch (Exception e) {
            log.error("添加失败:", e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "批量导入", notes = "插入")
    @PostMapping("/addAllLocalManualImport")
    public JsonResult addAllLocalManualImport(@RequestBody List<List<ProductDetailForm>> list){//批量导入多个产品
        //先过滤数据，剔除已经导入过的数据
        for (int i=0;i<list.size();i++){
            for (int j = list.get(i).size() - 1; j >= 0; j--) {
                if (mostUsedKnifeListService.findAllDetailId().contains(list.get(i).get(j).getId())){
                    list.get(i).remove(j);
                }
            }
            if(list.get(i).size()==0){
                list.remove(i);
            }
        }
        if(list.size()==0){
            return JsonResult.success("数据已全部导入");
        }
        for (int i=0;i<list.size();i++){
            addLocalManualImport(list.get(i));
        }
        return JsonResult.success("添加成功");
    }


    @ApiOperation(value = "本地仓库导入常用刀具", notes = "企业导入")
    @PostMapping("/addLocalManualImport")
    //单个规格和整个产品插入
    public JsonResult addLocalManualImport(@RequestBody List<ProductDetailForm> list){
        mostUsedKnifeListService.addLocalManualImport(list);
        return JsonResult.success("添加成功");
    }

    /**
     * 新·添加自采
     *
     * @param productForm
     * @return
     */
    @ApiOperation(value = "添加自采产品")
    @PostMapping("/addSelfPickProduct")
    public JsonResult addSelfPickProduct(@RequestBody ProductForm productForm){
     try {
        mostUsedKnifeListService.saveSelfPickProduct(productForm);
        return JsonResult.success("添加成功");
        }catch (Exception e) {
            log.error("添加失败:", e);
            return JsonResult.fail(e.getMessage());
        }
    }


    @ApiOperation(value = "修改sku信息", notes = "修改")
    @PutMapping("/updateProductDetailById")
    public JsonResult updateProductDetailById(@Validated(ProductDetailForm.Update.class) @RequestBody ProductDetailForm productDetailForm) {
        ProductDetail productDetail = productDetailService.getById(productDetailForm.getId());
        if(productDetail == null){
            return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(ProductDetail.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(productDetailForm, productDetail, copyOptions);
        if(productDetailForm.getLifeUnit()!=null){
            if(productDetailForm.getLifeUnit().equals(ProductDetail.LifeUnit.minute.getValue())){
                productDetail.setLifeUnit(ProductDetail.LifeUnit.minute);
            }else if(productDetailForm.getLifeUnit().equals(ProductDetail.LifeUnit.number.getValue())){
                productDetail.setLifeUnit(ProductDetail.LifeUnit.number);
            }
        }
        if (productDetailService.updateById(productDetail)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }


    @ApiOperation(value = "作废sku信息", notes = "作废")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/disable")
    public JsonResult disable(@Validated(ProductDetailForm.Add.class) ProductDetailForm productDetailForm) {
        // 判断当前物料是否已存在库存数据
        ProductDetailVO detailVO = productDetailService.get4appById(productDetailForm.getId());
        if((null != detailVO.getQuantity() && detailVO.getQuantity() > 0) || (null != detailVO.getQuantityCab() && detailVO.getQuantityCab() > 0)){
            return JsonResult.fail("当前物料已有库存数据，不可删除");
        }
        if(null != detailVO.getInventoryQuantity() && detailVO.getInventoryQuantity()>0){
            return JsonResult.fail("当前物料已有领新柜库存数据，不可删除");
        }
        if(null != detailVO.getStorageQuantity() && detailVO.getStorageQuantity()>0){
            return JsonResult.fail("当前物料已有暂存柜库存数据，不可删除");
        }
        ProductDetail productDetail=new ProductDetail();
        productDetail.setId(productDetailForm.getId());
        productDetail.setIsDeleted(true);
        if (mostUsedKnifeListService.updateById(productDetail)) {
            return JsonResult.success("停用成功");
        }
        return JsonResult.fail("停用失败");
    }

    /**
     * 添加产品（简版）
     * @param productForm
     * @return
     */
    @ApiOperation(value = "添加产品（简版）")
    @PostMapping("/addCompactProduct")
    public JsonResult addCompactProduct(ProductForm productForm){
        try {
            mostUsedKnifeListService.addCompactProduct(productForm);
            return JsonResult.success("添加成功");
        }catch (Exception e) {
            log.error("添加产品（简版）失败:", e);
            return JsonResult.fail(e.getMessage());
        }
    }
    /**
     * 添加产品（简版）
     * @param productForm
     * @return
     */
    @ApiOperation(value = "添加产品（简版）")
    @PostMapping("/syncCompactProduct")
    public JsonResult syncCompactProduct(@RequestBody ProductForm productForm){
        try {
            mostUsedKnifeListService.addCompactProduct(productForm);
            return JsonResult.success("添加成功");
        }catch (Exception e) {
            log.error("添加产品（简版）失败:", e);
            return JsonResult.fail(e.getMessage());
        }
    }
    /**
     * 设置安全库存
     * @param productDetailForm
     * @return
     */
    @ApiOperation(value = "设置安全库存")
    @PostMapping("/setSafetyInventory")
    public JsonResult setSafetyInventory(@RequestBody ProductDetailForm productDetailForm){
        ProductDetail productDetail = productDetailService.getById(productDetailForm.getId());
        if(productDetail == null){
            return JsonResult.fail("设置失败");
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(ProductDetail.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(productDetailForm, productDetail, copyOptions);
        if (productDetailService.updateById(productDetail)) {
            return JsonResult.success("设置成功！");
        }
        return JsonResult.fail("设置失败！");
    }

    @ApiOperation(value = "修改产品（简版）", notes = "修改")
    @PutMapping("/updateCompactProduct")
    public JsonResult updateCompactProduct(ProductForm productForm) {
        ProductDetail productDetail = productDetailService.getById(productForm.getId());
        if(productDetail == null){
            return JsonResult.fail("修改失败");
        }
        try {
            mostUsedKnifeListService.updateCompactProduct(productForm);
            return JsonResult.success("修改成功");
        }catch (Exception e) {
            log.error("修改产品（简版）失败:", e);
            return JsonResult.fail(e.getMessage());
        }
    }

}

